package com.pz.gulimall.product.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.retry.MessageRecoverer;
import org.springframework.amqp.rabbit.retry.RepublishMessageRecoverer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 消费者可靠性配置
 */
@Slf4j
@Configuration
//当配置了spring.rabbitmq.listener.simple.retry.enable=true 这个配置类才会生效
@ConditionalOnProperty(prefix = "spring.rabbitmq.listener.simple.retry", name = "enabled",havingValue = "true")
public class MqErrorConfig {
    private static final String errorExchange = "error.exchange";
    private static final String errorRoutingKey = "error";

    /**
     *  接收错误消息的交换机
     */
    @Bean
    public DirectExchange errorExchange(){
        return new DirectExchange(errorExchange);
    }

    @Bean
    public Queue errorQue(){
        return new Queue("error.que");
    }

    @Bean
    public Binding errorBinding(DirectExchange errorExchange, Queue errorQue){
        return BindingBuilder.bind(errorQue).to(errorExchange).with(errorRoutingKey);
    }

    @Bean
    public MessageRecoverer republishMsgRecovered(RabbitTemplate rabbitTemplate){
        return new RepublishMessageRecoverer(rabbitTemplate, errorExchange, errorRoutingKey);
    }
}
